package com.donger.common.messgae.handler;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.donger.common.messgae.config.SmsAliyunPropertiesConfig;
import com.donger.common.messgae.handler.MessageHandler;
import com.donger.common.messgae.template.SmsTemplate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 7326
 */
@Slf4j
@AllArgsConstructor
public class SmsAliyunMessageHandler implements MessageHandler<SmsTemplate> {
    private final SmsAliyunPropertiesConfig config;

    private static final String ACTION = "SendSms";
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";

    @Override
    public void check(SmsTemplate smsTemplate) throws Exception {
        if (StrUtil.isEmpty(smsTemplate.getAddress())) {
            throw new Exception("手机号不能为空");
        }
        if (StrUtil.isEmpty(smsTemplate.getContentTemplate())) {
            throw new Exception("短信内容不能为空");
        }
    }

    @Override
    public boolean process(SmsTemplate smsTemplate) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", config.getAccessKey(), config.getSecretKey());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion("2017-05-25");
        request.setAction(ACTION);
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", smsTemplate.getAddress());
        request.putQueryParameter("SignName", smsTemplate.getSignName());
        request.putQueryParameter("TemplateCode", smsTemplate.getTemplate());
        request.putQueryParameter("TemplateParam", smsTemplate.getContentTemplate());
        try {
            CommonResponse response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public void fail(SmsTemplate smsTemplate) {
        log.error("阿里云短信发送失败 - > 手机号: {} ", smsTemplate.getAddress());
    }
}
